// // ******************************************************************
// //       /\ /|       @file       TranslationRecordQueryHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-02-20 21:02
// //    *(__\_\        @Copyright  Copyright (c) , 2025-02-04 14:02 Await
// // ******************************************************************

using System.Linq.Expressions;
using AutomaticSubtitles.Contracts.Dto;
using AutomaticSubtitles.Service.Application.Translate.Interface.Queries;
using AutomaticSubtitles.Service.Application.TranslationRecord.Queries;
using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Translate;
using AutomaticSubtitles.Service.DataAccess;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace AutomaticSubtitles.Service.Application.TranslationRecord;

public class TranslationRecordQueryHandler
{
    private readonly ITranslationRecordRepository _repository;

    public TranslationRecordQueryHandler(ITranslationRecordRepository repository)
    {
        _repository = repository;
    }

    [EventHandler]
    public async Task Handle(GetTranslationRecordListQuery query)
    {
        // 获取数据
        (List<Auto_TranslationRecord> records, long totalCount) = await _repository.GetTranslationRecordsAsync(
            mediaId: query.Data.mediaId,
            mediaName: query.Data.mediaName,
            name: query.Data.name,
            translatedLanguage: query.Data.translatedLanguage,
            startTime: query.Data.startTime,
            endTime: query.Data.endTime,
            sortField: query.Data.sortField,
            sortOrder: query.Data.sortOrder,
            pageSize: query.Data.PageSize,
            pageIndex: query.Data.Page);

        // 计算总页数
        var totalPages = (int)Math.Ceiling(totalCount / (double)query.Data.PageSize);

        // 转换为DTO并设置分页信息
        query.Result = new PaginatedResponseDto<TranslationRecordDto>
        {
            Total = totalCount,
            TotalPages = totalPages,
            Result = records.Select(x => new TranslationRecordDto
            {
                Id = x.Id,
                MediaId = x.MediaId,
                MediaName = x.AutoMedia.Name,
                MediaPath = x.AutoMedia.Path,
                Name = x.Name,
                TranslatedLanguage = x.TranslatedLanguage,
                TranslatedPath = x.TranslatedPath,
                CreateTime = x.CreateTime
            }).ToList()
        };
    }
}